package com.saunter.utils.exception;

import com.saunter.utils.response.Response;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.env.Environment;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import javax.annotation.Resource;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {
    @Resource
    private Environment environment;

    private static Log LOG = LogFactory.getLog(GlobalExceptionHandler.class);

    @ExceptionHandler
    public Map<String, Object> handleException(Exception e) {
//        e.printStackTrace();
        if(e instanceof  CustomException) {
            CustomException exception = (CustomException)e;
            return Response.error(exception.getCode(), exception.getMsg(), exception.getData());
        }else {
            String error_code = "Se000";
            // mysql exception
            if(e instanceof DataAccessException) {
                error_code = e instanceof DuplicateKeyException ? "Sql001" : e instanceof DataIntegrityViolationException ? "Sql003" : "Sql000";
            }
            // servlet exception
            if(e instanceof MissingServletRequestParameterException || e instanceof MissingServletRequestPartException) {
                error_code = "Prm001";
            }else if(e instanceof MethodArgumentTypeMismatchException) {
                error_code = "Prm002";
            }else if(e instanceof HttpRequestMethodNotSupportedException) {
                error_code = "Met001";
            }else {
                LOG.error(e.getMessage());
            }
            return Response.error(error_code, environment.getProperty(error_code));
        }
    }
}
